package com.mxf.code.service.impl;


import com.mxf.code.common.ResponseResult;
import com.mxf.code.pojo.bo.LoginUser;
import com.mxf.code.pojo.entity.SysUser;
import com.mxf.code.service.LoginService;
import com.mxf.code.util.JwtUtils;
import com.mxf.code.util.RedisUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author : [mxf]
 * @version : [v1.0]
 * @className : LoginServiceImpl
 * @description : [描述说明该类的功能]
 * @createTime : [2022/9/3 20:17]
 * @updateUser : [mxf]
 * @updateTime : [2022/9/3 20:17]
 * @updateRemark : [描述说明本次修改内容]
 */
@Service
public class LoginServiceImpl implements LoginService {


    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private RedisUtils redisUtils;


    @Resource
    private RedisTemplate<String, LoginUser> redisTemplate;


    @Override
    public ResponseResult<Map<String, Object>> login(SysUser user) {

        //AuthenticationManager authenticate进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //如果认证没通过，给出对应的提示
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("登录失败");
        }
        //如果认证通过了，使用userid生成一个jwt /wt存入ResponseResult返回
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String jwt = JwtUtils.createJWT(loginUser.getUser().getId().toString());
        //把完整的用户信息存入redis userid作为key
        redisUtils.set("login:" + loginUser.getUser().getId(), RedisUtils.serialize(loginUser), 10 * 60L);
        HashMap<String, Object> map = new HashMap<>();
        map.put("token", jwt);
        return new ResponseResult<>(200, map, "登录成功");
    }

    @Override
    public ResponseResult<Map<String, Object>> logout() {
        UsernamePasswordAuthenticationToken authentication =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        redisUtils.del("login:" + loginUser.getUser().getId());
        return new ResponseResult<>(200, null, loginUser.getUsername() + "推出登录");
    }
}
